<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table border stripe :data="getRolesList">
        <el-table-column type="expand">
          <!-- 作用域插槽获取该行所有数据信息 -->
          <template slot-scope="scope">
            <el-row
              :class="['tablebottom',index1===0?'tablehead':'','vcenter'] "
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2===0?'':'tablehead','vcenter']"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="changeRoledialogVisible(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deletetRoledialogVisible(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addFromClosed">
      <el-form
        :model="addRolesList"
        status-icon
        :rules="FormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input type="text" v-model="addRolesList.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input type="text" v-model="addRolesList.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色信息框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoledialogVisible"
      width="50%"
      @close="editFromClosed"
    >
      <el-form
        :model="editFrom"
        label-width="100px"
        :rules="FormRules"
        status-icon
        ref="editFromRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input type="text" v-model="editFrom.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input type="text" v-model="editFrom.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoledialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="changeRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色权限树 -->
    <el-dialog title="分配权限" :visible.sync="rightdialogVisible" width="50%" @close="setRightDialogCloced">
      <!-- 树形控件 -->
      <el-tree
        :data="getRightList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defkeys"
        ref="alloTreeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightdialogSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 存放获取到的角色数据
      getRolesList: [],
      // 存放获取到的权限数据
      getRightList: [],
      // 添加角色的表单数据
      // 存放角色默认已有的权限id
      defkeys: [],
      addRolesList: {
        roleName: '',
        roleDesc: ''
      },
      // 存放当前角色id
      RoleID:'',

      // 修改角色的表单数据
      editFrom: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 添加角色信息
      addDialogVisible: false,

      // 修改角色
      editRoledialogVisible: false,

      // 权限分配
      rightdialogVisible: false,

      // 新增角色信息预验证
      FormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 权限数据树渲染
      treeProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    // 获取角色列表
    async getRoles() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')

      this.getRolesList = res.data
    },

    // 添加角色
    addRoles() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发起用户请求
        const { data: res } = await this.$http.post('roles', this.addRolesList)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        } else {
          // 隐藏添加角色框
          this.addDialogVisible = false
          this.$message.success('添加角色成功')
          // 刷新界面
          this.getRoles()
        }
      })
    },
    // 监听添加用户框的开关情况，并清除填写内容
    addFromClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 通过id查询角色信息
    async changeRoledialogVisible(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('修改角色信息失败')
      }
      this.editFrom = res.data
      // 显示修改角色信息弹出框
      this.editRoledialogVisible = true
    },

    // 对没有修改成功的表单数据进行清空
    editFromClosed() {
      this.$refs.editFromRef.resetFields()
    },
    // 修改角色信息
    changeRoles() {
      this.$refs.editFromRef.validate(async valid => {
        const { data: res } = await this.$http.put(
          'roles/' + this.editFrom.roleId,
          {
            roleName: this.editFrom.roleName,
            roleDesc: this.editFrom.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败')
        } else {
          this.$message.success('修改角色信息成功')
          // 更新角色信息
          this.getRoles()
          this.editRoledialogVisible = false
        }
      })
    },

    // 删除角色
    async deletetRoledialogVisible(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          canceButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message('已取消删除')
      } else {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) this.$message.error('删除角色信息失败')
        // 显示修改成功提示信息
        this.$message.success('删除角色信息成功')

        // 刷新页面，更新数据
        this.getRoles()
      }
    },
    // 删除权限数据
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该该内容, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        )
        if (res.meta.status !== 200) return this.$message.error('取消权限失败')

        this.$message.success('取消权限成功')
        // 更新该行数据
        role.children = res.data
      }
    },

    // 分配权限事件弹框
    async showSetRightDialog(role) {
      // 把当前角色的id进行保存
      this.RoleID=role.id
      const { data: res } = await this.$http.get('rights/tree')
      if(res.meta.status!==200){
        this.$message.error('获取权限数据失败！')
      }
      this.getRightList = res.data
      // console.log(this.getRightList)
      // 递归获取权限id
      this.getLeftKey(role,this.defkeys)
      this.rightdialogVisible = true
    },
    // 通过递归的方式获取所有三级权限的id,并存放到指定数组
    getLeftKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeftKey(item, arr))
    },
    // 每一次点击对话框都会往存放id的数组中添加三级id，即使关闭也不会被清空，导致错误显示
    setRightDialogCloced(){
      // 每一次关闭树形对话框都清空数组
      this.defkeys=[]
    },
    // 为角色分配权限
  async rightdialogSure(){
      const keys = [
        ...this.$refs.alloTreeRef.getCheckedKeys(),
        ...this.$refs.alloTreeRef.getHalfCheckedKeys()
      ]
    const  rids=keys.join(',')

    const{data:res} = await this.$http.post(`roles/${this.RoleID}/rights`,{rids:rids})
    if(res.meta.status!==200){
      return this.$message.error('分配角色权限失败！')
    }
     this.$message.success('分配角色权限成功！')
      this.getRoles()
      this.rightdialogVisible=false
    }
  },
  components: {}
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.tablebottom {
  border-bottom: 1px solid #eee;
}
.tablehead {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>

